import { createRouter, createWebHistory } from 'vue-router'
import { getToken, getUserInfo } from '../utils/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      redirect: '/Login',
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/RegisterView.vue'),
    },
    {
      path: '/Login',
      name: 'Login',
      component: () => import('@/views/LoginView.vue'),
    },
    //设置动态路由
    {
      path: '/admin',
      name: 'admin',
      component: () => import('@/views/AdminView.vue'),
      meta: {
        requiresAuth: true,
        requiredRole: 'admin',
      },
    },
    {
      path: '/traffic',
      name: 'traffic',
      component: () => import('@/views/TrafficView.vue'),
      meta: {
        requiresAuth: true,
        requiredRole: 'traffic',
      },
    },
    {
      path: '/normal',
      name: 'normal',
      component: () => import('@/views/NormalView.vue'),
      meta: {
        requiresAuth: true,
        requiredRole: 'normal',
      },
    },
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    // 检查是否有token
    const token = getToken()
    if (!token) {
      ElMessage.error('请先登录')
      next({ path: '/Login' })
      return
    }
    // 检查用户角色
    const userInfo = getUserInfo()
    if (!userInfo) {
      ElMessage.error('用户信息不存在，请重新登录')
      next({ path: '/Login' })
      return
    }
    // 检查用户角色是否匹配路由要求的角色
    const requiredRole = to.meta.requiredRole
    if (requiredRole && userInfo.role !== requiredRole) {
      ElMessage.error('没有权限访问该页面')
      // 根据用户当前角色重定向到对应的页面
      next({ path: `/${userInfo.role}` })
      return
    }
    // 通过所有检查，允许访问
    next()
  } else {
    // 不需要认证的路由直接通过
    next()
  }
})

export default router
